import _ from 'lodash';
import koa from 'koa';
import Router from '@koa/router';
import handle from '../handle';

import * as boom from '@hapi/boom';
import * as service from './service';

import { PostFormat, PostId } from './model';
import { User, UserId } from '../user/model';
import { auth } from '../middlewares/auth';

const router = new Router();

async function getPostInfo(ctx: koa.Context) {
  const postId = +ctx.params.postId;
  const post = service.getPost(postId);
  if (!post) {
    throw boom.notFound('文章不存在');
  }
  return post!;
}

interface SavePostData {
  postId?: PostId;
  title: string;
  content: string;
  format: PostFormat;
}

async function savePost(ctx: koa.Context) {
  const user = (ctx as any).user as User;
  // TODO: 人工硬转一下可能会更好
  const data = ctx.request.body as unknown as SavePostData;
  if (data.postId !== null && data.postId !== undefined) {
    await service.update({
      postId: data.postId!,
      userId: user.id,
      title: data.title,
      content: data.content,
      format: data.format,
    });
    return { postId: data.postId };
  } else {
    const postId = await service.create({
      userId: user.id,
      title: data.title,
      content: data.content,
      format: data.format,
    });
    return { postId };
  }
}

async function getUserPost(ctx: koa.Context) {
  const user = (ctx as any).user as User;
  return await service.getUserPost(user.id);
}

router.post('/', auth, handle(savePost));
router.get('/', auth, handle(getUserPost));
router.get('/:postId', handle(getPostInfo));

export default router;
